//
//  LBHomeController.m
//  爱鲜蜂
//
//  Created by 李田 on 16/11/7.
//  Copyright © 2016年 tianyao. All rights reserved.
//

#import "LBHomeController.h"
#import "LBHomeFunctionListView.h"
#import "LBTopNextController.h"
#import "DSHTTPClient.h"
#import "AXFNetworkingTools.h"
#import "LBActInfoModel.h"
#import "LBNavBarView.h"

#import "UINavigationBar+Awesome.h"
#import "LBHomeFunctionListView.h"
#import "PYSearch.h"


#import "UINavigationBar+YBZY.h"
#import "UIImage+Convenience.h"
#import "UIImage+YSCutIOutCircle.h"


#import <CoreLocation/CoreLocation.h>
#import "TQLocationConverter.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import "SubLBXScanViewController.h"


#import "LBNavigationView.h"

#import "LBActRowsModel.h"
#import "LBImgModel.h"
#import "LBSuperMarketViewController.h"

#import "LBNavigationController.h"
#define NAVBAR_CHANGE_POINT 20

@interface LBHomeController ()<CLLocationManagerDelegate,BMKMapViewDelegate, LBHomeFunctionListViewDelegate>
// 数组model
@property(weak,nonatomic)LBHomeFunctionListView  *HomeController;

@property(assign,nonatomic)CGFloat record;
@property(weak,nonatomic)UIBarButtonItem  *leftBtnItem;
@property(weak,nonatomic)UIBarButtonItem  *rightBtnItem;
@property(weak,nonatomic)UIButton      *barButtonItemView;
@property (nonatomic, strong) CLLocationManager *locationManager;

@property (nonatomic, copy) NSString *locateString;

@property (nonatomic,weak) BMKMapView *mapView;

@property (nonatomic,weak) UIButton *addressButton;

@property (nonatomic,assign) CGFloat spacing;


@property (nonatomic, strong) NSMutableArray *actRowsArray;

@property(weak,nonatomic)LBNavigationView  *NaviView;

@property(assign,nonatomic)CGFloat Alpha;

@property(nonatomic, strong)NSArray<LBImgModel *> *imgDataList;

@end

@implementation LBHomeController{
    
    
}

- (void)homeFunctionListView:(LBHomeFunctionListView *)homeFunctionListView indexPathSection:(NSUInteger)section{
    
//    LBNavigationController *NavVC = (LBNavigationController *)self.tabBarController.childViewControllers[1];
//    
//    LBSuperMarketViewController *VC = (LBSuperMarketViewController *)NavVC.childViewControllers[0];
//    
//    VC.leftRow = section;
//    
//    [self.tabBarController setSelectedIndex:1];
    
    LBSuperMarketViewController *VC = [[LBSuperMarketViewController alloc]init];
    
    VC.leftRow = section;
    
    [self.navigationController pushViewController:VC animated:YES];
}


- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];

    if(self.record<55){
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    }
    
    
    
    
}

-(void)navigation{
    
    LBNavigationView *Naview = [[[NSBundle mainBundle]loadNibNamed:@"LBNavigationView" owner:self options:nil]lastObject];
    self.NaviView = Naview;
    
    [self.NaviView.leftbtn addTarget:self action:@selector(QRScan) forControlEvents:(UIControlEventTouchUpInside)];
    [self.NaviView.rightbtn addTarget:self action:@selector(Seach) forControlEvents:(UIControlEventTouchUpInside)];
    
    Naview.frame = CGRectMake(0, 0, 375, 64);
    [self.view addSubview:Naview];
}



#pragma mark - 控制器View已经消失的时候
- (void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
            //    [self.navigationController.navigationBar lt_reset];
    self.navigationController.toolbarHidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [LBPlusMinusTool sharedPlusMinusTool].location = self.locateString;
    

}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    //渐变导航条通知监听
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeNavigation:) name:@"offset" object:nil];
    [self navigation];
    
    [self loadData];
    
    [self locate];
    
    CGFloat width =  self.NaviView.locationbtn.bounds.size.width;
    
    CGFloat height = self.NaviView.locationbackground.bounds.size.height;
    
    self.NaviView.locationbackground.bounds = CGRectMake(0, 0, width, height);
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(btnClick:) name:@"button" object:nil];
    
}

- (void)btnClick: (NSNotification *)no{
    
    UIButton *btn = no.object;
    
    switch (btn.tag) {
        case 1:
            btn.tag = 0;
            break;
        case 2:
            btn.tag = 3;
            break;
        case 3:
            btn.tag = 4;
            break;
        case 4:
            btn.tag = 0;
        default:
            break;
    }
    
//    LBNavigationController *NavVC = (LBNavigationController *)self.tabBarController.childViewControllers[1];
//    
//    LBSuperMarketViewController *VC = (LBSuperMarketViewController *)NavVC.childViewControllers[0];
//    
//    VC.leftRow = btn.tag;
//    
//    [self.tabBarController setSelectedIndex:1];

    LBSuperMarketViewController *VC = [[LBSuperMarketViewController alloc]init];
    
    VC.leftRow = btn.tag;
    
    [self.navigationController pushViewController:VC animated:YES];
    
    
}

//
////MARK:重加载刷新Navigation方法
//
//-(void)reloadNavigationItemViewAlpha:(CGFloat)alpha leftImageName:(NSString *)leftImage rightImageName:(NSString *)rightImage TitleColor:(UIColor*)titleColor arrowImage:(NSString *)arrowName{
//    //    [self.navigationItem setLeftBarButtonItem:nil];
//    //    [self.navigationItem setRightBarButtonItem:nil];
//    //    [self.navigationItem setTitleView:nil];
//    [self NavigationBarTitleViewSetupUI:alpha leftImageName:leftImage rightImageName:rightImage TitleColor:titleColor arrowImage:arrowName];
//
//}
//
////设置navigation界面
//
//- (void)NavigationBarTitleViewSetupUI:(CGFloat)alpha leftImageName:(NSString *)leftImage rightImageName:(NSString *)rightImage TitleColor:(UIColor*)titleColor arrowImage:(NSString *)arrowName{
//
//    //MARK:左右图标设置
//
//    UIBarButtonItem *rightBtnItem = [self barButtonItemWithImageName:rightImage withBackgroundAlpha:alpha tag:2];
//
//
//    //    self.rightBtnItem = rightBtnItem;
//
//
//
//    UIBarButtonItem *leftBtnItem = [self barButtonItemWithImageName:leftImage withBackgroundAlpha:alpha tag:1];
//    //    self.leftBtnItem = leftBtnItem;
//
//
//
//    [self.navigationItem setRightBarButtonItem:rightBtnItem];
//
//    [self.navigationItem setLeftBarButtonItem:leftBtnItem];
//
//
//    //MARK:中间位置的设置
//
//    //Button作为
//    UIButton *addressButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 200, 30)];
//    if(self.locateString){
//
//        [addressButton setTitle:[NSString stringWithFormat:@"配送至：%@",self.locateString] forState:UIControlStateNormal];
//        [addressButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
//        [addressButton setTitleColor:titleColor forState:UIControlStateNormal];
//        [addressButton setImage:[UIImage imageNamed:arrowName] forState:UIControlStateNormal];
//
//        CGSize imageSize = addressButton.imageView.frame.size;
//
//        CGSize titleSize = addressButton.titleLabel.frame.size;
//
//        addressButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageSize.width * 2 - 4.0, 0, 0);
//        addressButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, -2, -titleSize.width * 2 - 4.0);
//    }
//    //测试预设配送地址的文本，大小，颜色
//    else{
//        [addressButton setTitle:@"配送至：搜索中..." forState:UIControlStateNormal];
//        [addressButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
//        [addressButton setTitleColor:titleColor forState:UIControlStateNormal];
//        [addressButton setImage:[UIImage imageNamed:arrowName] forState:UIControlStateNormal];
//
//        CGFloat spacing = 4.0;
//        //        _spacing = spacing;
//
//        CGSize imageSize = addressButton.imageView.frame.size;
//
//        CGSize titleSize = addressButton.titleLabel.frame.size;
//
//        addressButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageSize.width * 2 - spacing, 0, 0);
//        addressButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, -2, -titleSize.width * 2 - spacing);
//
//    }
//    //底部图片颜色
//    [addressButton setBackgroundImage:[[UIImage ybzy_imageWithColor:[UIColor colorWithWhite:0 alpha:alpha] size:CGSizeMake(200, 30)] ybzy_cornerImageWithSize:CGSizeMake(200, 30) fillColor:[UIColor clearColor]] forState:UIControlStateNormal];
//
//    self.barButtonItemView = addressButton;
//
//
//
//    //    self.addressButton = addressButton;
//    //按键点击事件，跳转到配送页面（送货上门/店铺自提）
//    //未实现，预留方法
//
//
//    //    [addressButton addTarget:self action:@selector(addressButtonClick) forControlEvents:UIControlEventTouchUpInside];
//
//
//
//    //将addressButton作为Navigation的titleView添加上，居中
//    self.navigationItem.titleView = addressButton;
//
//    //传值
//    //self.addressButton = addressButton;
//
//
//    //        self.navigationController.navigationBar.alpha = 0.2;
//    //    NSLog(@"%f",self.navigationController.navigationBar.alpha);
//
//}

//二维码
-(void)QRScan{
    
    SubLBXScanViewController *QrVc = [[SubLBXScanViewController alloc]init];
    
    
    [self.navigationController pushViewController:QrVc animated:YES];
}

//搜索
-(void)Seach{
    
    NSArray *hotSearchs = @[@"水", @"大闸蟹", @"中秋月饼", @"酸奶",@"啤酒", @"西瓜", @"大荔冬枣", @"贝儿蛋糕", @"方便面", @"酸奶"];
    
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:hotSearchs searchBarPlaceholder:@"Search programming language" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        
        [searchViewController.navigationController pushViewController:[[UIViewController alloc] init] animated:YES];
    }];
    
    searchViewController.hotSearchStyle = PYHotSearchStyleColorfulTag;
    searchViewController.searchHistoryStyle = PYSearchHistoryStyleBorderTag;
    //    searchViewController.searchResultShowMode = PYSearchResultShowModeEmbed;
    //    searchViewController.searchSuggestionHidden = YES;
    
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:searchViewController];
   
    [self presentViewController:navVC animated:YES completion:nil];
}
//
//
//
//#pragma mark - 自定义导航条左右按钮
//- (UIBarButtonItem *)barButtonItemWithImageName: (NSString *)imageName withBackgroundAlpha:(CGFloat )imageAlpha tag: (TYNextVcTag)tag{
//
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//
//    //自定义颜色,转换图片
//    UIImage *image = [[UIImage ybzy_imageWithColor:[UIColor colorWithWhite:0 alpha:imageAlpha] size:CGSizeMake(200, 30)] ybzy_cornerImageWithSize:CGSizeMake(200, 30) fillColor:[UIColor clearColor]];
//
//
//
//    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
//    [btn setBackgroundImage:[image circleParam:1] forState:UIControlStateNormal];
//
//    btn.frame = CGRectMake(0, 0, 30,30);
//
//    //    btn.layer.cornerRadius =15 ;
//
//
//    btn.tag = tag;
//
//
//    //给按钮添加方法.使按钮可被点击
//    if (btn.tag == 1) {
//        [btn addTarget:self action:@selector(QRScan) forControlEvents:UIControlEventTouchUpInside];
//
//    }
//    if(btn.tag == 2){
//        [btn addTarget:self action:@selector(Seach) forControlEvents:UIControlEventTouchUpInside];
//    }
//    UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
//    return btnItem;
//
//}
//

#pragma mark - 1.0 创建collectionView
- (void)setupUI{
    self.navigationController.navigationBar.alpha = 0;
    
    LBHomeFunctionListView *functionView  =  [[LBHomeFunctionListView alloc] init];
    
    [self.view addSubview:functionView];
    _HomeController = functionView;
    
    //    MARK: 代理
    self.HomeController.delegate = self;
    
    // 布局
    [functionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view);
    }];
    
    
}

#pragma mark - 2.0 加载数据
- (void)loadData{
    
    //    MARK: 从git请求数据
    [[AXFNetworkingTools sharedManager] getHomeDataComplete:^(id responseOBJ, NSError *error) {
        
        [responseOBJ writeToFile:@"/Users/tianyao/Desktop/home1/home1.plist" atomically:NO];
        
        NSDictionary *dataDict = responseOBJ[@"data"];
        NSArray<NSDictionary *> *actInfo = dataDict[@"act_info"];
        
        NSArray *arr = [NSArray yy_modelArrayWithClass:[LBActInfoModel class] json:actInfo];
        _actRowsArray = arr.copy;
        _HomeController.actInfoModelArray = arr.copy;
        
        //      NSArray *arr1 = [NSArray yy_modelArrayWithClass:[LBActRowsModel class] json:actInfo[4]];
        
    }];
    
    //    MARK: 解析plist
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"img.plist" withExtension:nil];
    NSArray<NSDictionary *> *arr = [NSArray arrayWithContentsOfURL:url];
    
    NSMutableArray<LBImgModel *> *arrayM = [NSMutableArray arrayWithCapacity:10];
    [arr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull dict, NSUInteger idx, BOOL * _Nonnull stop) {
        LBImgModel *imgModel = [LBImgModel yy_modelWithDictionary:dict];
        [arrayM addObject:imgModel];
    }];
    self.imgDataList = arrayM.copy;
    
    self.HomeController.imgDataList = self.imgDataList;
}


#pragma mark - 通知

-(void)changeNavigation:(NSNotification *)notifacation{
    
    NSDictionary *dic = notifacation.userInfo;
    
    CGFloat offsetY = [dic[@"offsetY"] floatValue];
    
    
    self.record = offsetY ;
    
    
    if(offsetY< 0)
    {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    }
    if (offsetY < 150) {
        
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
        
        self.Alpha =((160 - offsetY)/160);
        
        //        self.Alpha  = (1-((160 - offsetY)/160));
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
        [self.NaviView.leftbtn setImage:[UIImage imageNamed:@"icon_white_scancode"] forState:(UIControlStateNormal)];
        [self.NaviView.rightbtn setImage:[UIImage imageNamed:@"icon_search_white"] forState:UIControlStateNormal];
        [self.NaviView.locationbtn.titleLabel setTextColor:[UIColor whiteColor]];
        [self.NaviView.arrowbtn setImage:[UIImage imageNamed:@"control-down-white"] forState:UIControlStateNormal];
        self.NaviView.leftbackground.alpha = self.Alpha;
        self.NaviView.rightbackground.alpha = self.Alpha;
        self.NaviView.locationbackground.alpha = self.Alpha;
        self.NaviView.background.alpha = 1 - self.Alpha;
        
    }else{
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
        [self.NaviView.leftbtn setImage:[UIImage imageNamed:@"icon_black_scancode"] forState:(UIControlStateNormal)];
        [self.NaviView.rightbtn setImage:[UIImage imageNamed:@"icon_search_black"] forState:UIControlStateNormal];
        [self.NaviView.locationbtn.titleLabel setTextColor:[UIColor blackColor]];
        [self.NaviView.arrowbtn setImage:[UIImage imageNamed:@"control-down-black"] forState:UIControlStateNormal];
        self.NaviView.leftbackground.alpha = 0;
        self.NaviView.rightbackground.alpha = 0;
        self.NaviView.locationbackground.alpha = 0;
        
    }
    
    //    self.locationBtn.alpha = self.Alpha;
    
    

    
    
    
    
    
    
    //    if (offsetY < 160) {
    //
    //        _alpha =((160 - offsetY)/160);
    //
    //        _btnAlpha = (1-((160 - offsetY)/160));
    //
    //
    //    }
    //    CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT +134 - offsetY) / 154));
    
    
    //    NSLog(@"%f",_alpha);
    //
    //    NSLog(@"%f",_btnAlpha);
    //
    //    if (offsetY > NAVBAR_CHANGE_POINT) {
    //
    //        [self reloadNavigationItemViewAlpha:btnAlpha leftImageName:@"icon_white_scancode" rightImageName:@"icon_search_white" TitleColor:[UIColor whiteColor] arrowImage:@"control-down-white"];
    //
    //        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
    //
    //
    //        if(offsetY >110){
    //            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
    //            [self reloadNavigationItemViewAlpha:btnAlpha leftImageName:@"icon_black_scancode" rightImageName:@"icon_search_black" TitleColor:[UIColor blackColor]arrowImage:@"control-down-black"];
    //
    //            [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
    //        }
    //        else{
    //
    //            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    //            [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
    //                _once = YES;
    //
    //        }
    //
    //    }
    
}

//MARK:定位的代理方法


#pragma mark - 定位相关
- (void)locate {
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            [self.locationManager requestAlwaysAuthorization];
        }
        [self.locationManager startUpdatingLocation];
    }
    
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    [self.locationManager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    //反编码
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError *_Nullable error) {
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            self.locateString = placeMark.name;
            //              self.NaviView.locationbtn.titleLabel.text =placeMark.name;
            
            NSLog(@"%@",_locateString);
            if (!self.locateString) {
                self.locateString = @"无法定位具体位置";
                //                self.NaviView.locationbtn.titleLabel.text = @"无法定位具体位置";
            }
            
        } else if (error == nil && placemarks.count == 0) {
            self.locateString = @"无法定位具体位置";
            //              self.NaviView.locationbtn.titleLabel.text = @"无法定位具体位置";
        } else if (error) {
            
            self.locateString = @"无法定位具体位置";
            //              self.NaviView.locationbtn.titleLabel.text = @"无法定位具体位置";
        }
        
        //self.NaviView.locationbtn.titleLabel.text = self.locateString;
        
        [self.NaviView.locationbtn setTitle:[NSString stringWithFormat:@"配送至:%@",_locateString] forState:UIControlStateNormal];
        
        //        CGSize *rect = self.NaviView.locationbackground.frame.size;
        
        
        
    }];
    
}



-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(NSMutableArray *)actRowsArray{
    if (_actRowsArray == nil) {
        _actRowsArray = [NSMutableArray arrayWithCapacity:10];
    }
    return _actRowsArray;
}



@end
